package com.maoning.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.maoning.common.constant.AuthServerConstant;
import com.maoning.common.utils.HttpUtils;
import com.maoning.common.vo.SocialUser;
import com.maoning.common.vo.WeiboUserInfo;
import com.maoning.member.entity.MemberLevelEntity;
import com.maoning.member.exception.UserOrPasswordErrorException;
import com.maoning.member.vo.MemberLoginVo;
import com.maoning.member.vo.MemberRegistVo;
import com.maoning.member.exception.PhoneExistException;
import com.maoning.member.exception.UsernameExistException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoning.common.utils.PageUtils;
import com.maoning.common.utils.Query;

import com.maoning.member.dao.MemberDao;
import com.maoning.member.entity.MemberEntity;
import com.maoning.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo memberRegistVo) throws PhoneExistException,UsernameExistException{

        //需要检查手机号和姓名和唯一性
        this.checkPhoneUnique(memberRegistVo.getPhone());
        this.checkUserNameUnique(memberRegistVo.getUserName());

        final MemberEntity memberEntity = new MemberEntity();
        memberEntity.setMobile(memberRegistVo.getPhone());
        memberEntity.setUsername(memberRegistVo.getUserName());
        //这里给密码增加盐值
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        final String encodePassword = passwordEncoder.encode(memberRegistVo.getPassword());
        memberEntity.setPassword(encodePassword);
        MemberLevelEntity memberLevelEntity = this.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        this.save(memberEntity);
    }

    @Override
    public MemberLevelEntity getDefaultLevel() {
        return this.baseMapper.getDefaultLevel();
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        final MemberEntity mobile = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile != null){
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameExistException{
        final MemberEntity mobile = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (mobile != null){
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo){
        final MemberEntity one = this.getOne(new QueryWrapper<MemberEntity>().eq("mobile", memberLoginVo.getLoginacct()).or().eq("username", memberLoginVo.getLoginacct()));
        if (one == null){
            return null;
        }else {
            final String password = one.getPassword();
            final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            final boolean matches = passwordEncoder.matches(memberLoginVo.getPassword(), password);
            if(matches){
                return one;
            }else {
                return null;
            }
        }
    }

    /**
     * 微博社交登陆的方法
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity oauth2Login(SocialUser socialUser) {
        //判断当前用户是否已经注册过
        final MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUid()));

        if(Objects.nonNull(entity)){
            //已经注册过
            entity.setAccessToken(socialUser.getAccessToken());
            entity.setExpiresIn(socialUser.getExpiresIn());
            entity.setSocialUid(socialUser.getUid());
            this.updateById(entity);
            return entity;
        }else {
            final MemberEntity newEntity = new MemberEntity();
            newEntity.setAccessToken(socialUser.getAccessToken());
            newEntity.setExpiresIn(socialUser.getExpiresIn());
            newEntity.setSocialUid(socialUser.getUid());

            WeiboUserInfo userInfo = null;
            try {
                userInfo = this.getWeiboUserInfo(socialUser);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(Objects.nonNull(userInfo)){
                newEntity.setUsername(AuthServerConstant.OAUTH_WEIBO + userInfo.getName());
                newEntity.setNickname(userInfo.getName());
                newEntity.setCity(userInfo.getLocation());
                newEntity.setGender("m".equals(userInfo.getGender())?1:0);
                newEntity.setSign(userInfo.getDescription());
                MemberLevelEntity memberLevelEntity = this.getDefaultLevel();
                newEntity.setLevelId(memberLevelEntity.getId());
            }
            this.save(newEntity);
            return newEntity;
        }
    }

    private WeiboUserInfo getWeiboUserInfo(SocialUser socialUser) throws Exception {
        //
        String host = "https://api.weibo.com";
        String path = "/2/users/show.json";
        String method = "get";
        Map<String, String> querys = new HashMap<>();
        querys.put("access_token", socialUser.getAccessToken());
        querys.put("uid", socialUser.getUid());

        WeiboUserInfo weiboUserInfo = null;
        final HttpResponse resp = HttpUtils.doGet(host, path, method, null, querys, (Map<String, String>) null);
        if(resp.getStatusLine().getStatusCode() == 200){
            //获取成功
            final HttpEntity entity = resp.getEntity();
            final String json = EntityUtils.toString(entity);
            weiboUserInfo = JSONObject.parseObject(json, WeiboUserInfo.class);
            final String accessToken = socialUser.getAccessToken();
        }
        return weiboUserInfo;
    }

}